import { getStream } from '../Core/connect'
import { Object3D } from './Object3D'
import * as MathUtils from '../Math/MathUtils'
import { Vector2 } from '../Math/Vector2'

type spriteType = '2D' | '3D'

export class Sprite extends Object3D {
    readonly type: string
    spriteType: spriteType
    Offset?: Vector2
    constructor(name: string, url: string, Offset?: Vector2) {
        super({name: name, type: 'Sprite'})
        this.type = 'Sprite'
        this.spriteType = '2D'
        this.Offset = Offset ? Offset : new Vector2(0, 0)
        this.setUrl(url)
    }
    setUrl(url: string) {
        const stream = getStream()
        const str = {function: 'setSpriteImage', ids: `${this.uuid}`, url:`${url}`}
        stream.emitUIInteraction(str)
    }
    //设置锚点偏移
    setSpriteOffset(Offset: Vector2) {
        this.Offset = Offset
        const stream = getStream()
        const str = {function: 'setSpriteOffset', ids: `${this.uuid}`, Offset: `${this.Offset.x},${this.Offset.y}`}
        stream.emitUIInteraction(str)
    }
    setType(spriteType: spriteType) {
        this.spriteType = spriteType
        const stream = getStream()
        const str = {function: 'setSpriteType', ids: `${this.uuid}`, spriteType:`${spriteType}`}
        stream.emitUIInteraction(str)
    }
    setSpriteSize(size: Vector2) {
        const stream = getStream()
        const str = {function: 'setSpriteSize', ids: `${this.uuid}`, size:`${size.x},${size.y}`}
        stream.emitUIInteraction(str)
    }
    setClick(fun: Function) {
        const stream = getStream()
        const sessionId = MathUtils.generateUUID()
        const str = {function: 'setSpriteClick', ids: `${this.uuid}`, sessionId: sessionId}
        stream.emitUIInteraction(str)
        const getSpriteClick = (data: string) => {
            const returnData = JSON.parse(data)
            if (returnData.sessionId === sessionId) {
                fun(this)
            }
        }
        stream.addResponseEventListener(`spriteClick${this.uuid}`, getSpriteClick)
    }
}